package net.hongliang.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HtmlUtil {

	private static final String download = "\n<a href=\"$1\" target=\"_blank\">$1</a>\n";

	private static final HtmlUtil instance = new HtmlUtil();

	private static final Map map = new HashMap();

	private static Pattern p = Pattern.compile("(([a-zA-Z_]*?)://"
			+ "[a-zA-Z_0-9\\./\\?\\&;#-=%~,!]{3,}+)"
			+ "[^a-zA-Z_0-9\\./\\?\\&;#-=%~,!]");

	static {
		String content = null;

		content = "\n<a href=\"$1\" target=\"_blank\"><img src=\"$1\"/></a>\n";
		// image
		map.put("bmp", content);
		map.put("gif", content);
		map.put("jpe", content);
		map.put("jpeg", content);
		map.put("jpg", content);
		map.put("png", content);
		map.put("tif", content);
		map.put("tiff", content);

		content = download;

		// audio
		map.put("au", content);
		map.put("mid", content);
		map.put("midi", content);
		map.put("mp3", content);
		map.put("mpa", content);
		map.put("mpega", content);
		map.put("wav", content);

		// video
		map.put("asf", content);
		map.put("asx", content);
		map.put("avi", content);
		map.put("mov", content);
		map.put("mpe", content);
		map.put("mpeg", content);
		map.put("mpg", content);
		map.put("rm", content);

		// flash
		content = "\n<p>"
				+ "\n<a href=\"$1\" target=\"_blank\">全屏播放</a>"
				+ "(请鼠标右键点击Flash选择播放)"
				+ "\n<br/>"
				+ "\n<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" "
				+ "codebase=\"http://active.macromedia.com/flash5/cabs/swflash."
				+ "cab#version=5,0,0,0\">"
				+ "\n<param name=\"movie\" value=\"$1\">"
				+ "\n<param name=\"play\" value=\"false\">"
				+ "\n<param name=\"loop\" value=\"true\">"
				+ "\n<param name=\"quality\" value=\"high\">"
				+ "\n<embed src=\"$1\" play=\"false\" loop=\"true\""
				+ "\nquality=\"high\" pluginspage=\"http://www.macromedia.com/"
				+ "shockwave/download/index.cgi?"
				+ "\nP1_Prod_Version=ShockwaveFlash\">" + "\n</embed>"
				+ "\n</object>" + "\n</p>" + "\n";
		map.put("swf", content);
	}

	public static String escapeHtml(char ch) {
		String str = new StringBuffer(1).append(ch).toString();
		return escapeHtml(str);
	}

	/**
	 * escape basic html tag
	 * 
	 * @param s
	 * @return
	 */
	public static String escapeHtml(String s) {
		if (FieldUtil.isEmpty(s)) {
			return "";
		}

		String str = s;

		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("  ", " &nbsp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		str = str.replaceAll("\t", " &nbsp;&nbsp;&nbsp;&nbsp; ");
		str = str.replaceAll("\n", " <br/> ");

		return str;
	}

	/**
	 * escape more html tag
	 * 
	 * @param s
	 * @return
	 */
	public static String escapeMoreHtml(String s) {
		if (FieldUtil.isEmpty(s)) {
			return "";
		}

		String str = s + " "; // add a space at the end for regular expression

		Matcher m = p.matcher(str);

		String replace = null;
		Object obj;
		StringBuffer sb = new StringBuffer(str.length());
		char ch = ' ';
		int start = 0;

		while (m.find()) {
			if (m.groupCount() < 1) {
				continue;
			}

			// find a url, add the previous user's text to string buffer
			sb.append(escapeHtml(str.substring(start, m.start())));

			// get a replace string
			obj = map.get(getExt(m.group(1)).toLowerCase());

			// deal with the url, convert plain text to url with html tag
			if (obj == null) {
				replace = m.group(0).replaceAll(p.pattern(), download);
			} else {
				replace = m.group(0).replaceAll(p.pattern(), (String) obj);
			}

			// add the generated replaced text to string buffer
			sb.append(replace);

			// set the start
			start = m.end() - 1;
		}

		sb.append(escapeHtml(str.substring(start, str.length())));

		return sb.toString();

	}

	public static String escapeTextarea(String s) {
  System.out.println("area------------------------------------------"+s);
		if (FieldUtil.isEmpty(s)) {
			return "";
		}

		return s.replaceAll("</textarea>", "&lt;/textarea&gt;");
	}

	/**
	 * get the file extension name from url
	 * 
	 * @param url
	 * @return
	 */
	private static String getExt(String url) {
		String ext = null;
		int pos = -1;

		if (FieldUtil.isEmpty(url)) {
			return ext;
		}

		pos = url.indexOf('?');
		if (pos != -1) {
			url = url.substring(0, pos);
		}

		pos = url.indexOf('&');
		if (pos != -1) {
			url = url.substring(0, pos);
		}

		pos = url.indexOf('#');
		if (pos != -1) {
			url = url.substring(0, pos);
		}

		pos = url.lastIndexOf('.');
		if (pos != -1) {
			ext = url.substring(1 + pos);
		}

		return ext;
	}

	public static HtmlUtil getInstance() {
		return instance;
	}

	/**
	 * auto parse url in the string s and convert to its corresponding html tag
	 * such as a, img, embed...
	 * 
	 * ATTENTION: if the protocal(http, mms, rtsp...) starts at '_', the url
	 * will be parsed to a, not the img or embed or something else
	 * 
	 * @param s
	 * @return
	 */
	public static String parseUrl(String s) {
		String str = s + " "; // add a space at the end for regular expression

		Matcher m = p.matcher(str);

		String url = null;
		String protocol = null;
		String ext = null;
		String replace = null;
		Object obj;
		StringBuffer sb = new StringBuffer();
		char ch = ' ';

		while (m.find()) {
			if (m.groupCount() < 1) {
				continue;
			}

			protocol = m.group(2);
			ch = protocol.charAt(0);
			url = m.group(1);
			ext = getExt(url);
			obj = map.get(ext);
			if (obj == null) {
				replace = download;
			} else {
				replace = (String) obj;
			}

			if (ch == '_') {
				m.appendReplacement(sb, url.substring(1));
			} else {
				m.appendReplacement(sb, replace);
			}
		}

		m.appendTail(sb);

		return sb.toString();
	}

	/**
	 * unescape basic html tag, convert &xxx; to origin character
	 * 
	 * @param s
	 * @return
	 */
	public static String unescapeHtml(String s) {
		if (FieldUtil.isEmpty(s)) {
			return "";
		}

		String str = s;

		str = str.replaceAll(" <br/> ", "\n");
		str = str.replaceAll(" &nbsp;&nbsp;&nbsp;&nbsp; ", "\t");
		str = str.replaceAll("&quot;", "\"");
		str = str.replaceAll("&gt;", ">");
		str = str.replaceAll("&lt;", "<");
		str = str.replaceAll(" &nbsp;", "  ");
		str = str.replaceAll("&amp;", "&");

		return str;
	}

	private HtmlUtil() {

	}
}
